<template>
  <!--  group规则模板 -->
  <div>
    <!-- 按钮与搜索 -->
    <el-row class="groupRule container">
      <el-col style="margin-right: 10px" class="content-left">
        <!-- 操作区域 -->
        <upper-template
          exportIcon
          importIcon
          :configIcon="false"
          @search="(searchForm.page = 1), searchFunc()"
          @clear="
            (searchForm.groupRuleCode = ''),
            (searchForm.effectDate = ''),
            (searchForm.invalidDate = ''),
            (searchForm.assignPrice= '')
          "
        >
          <!-- 操作按钮区 -->
          <template slot="buttonArea" >
            <el-button @click="addOrEditFunc('1')">新增</el-button>
            <el-button @click="addOrEditFunc('2')">编辑</el-button>
            <el-button @click="delFunc()">删除</el-button>
          </template>
          <div slot="exportArea">
                  <!-- 导出操作区域 -->
              <el-button @click="exportExcel('1')"
              >导出模板</el-button>
              <el-button @click="exportExcel('2')"
              >导出数据</el-button> 
         </div>
          <!-- 导入 -->
          <div slot="importArea">
                  <!-- 导入操作区域 -->
                  <el-upload
                    accept=".xls, .xlsx"
                    ref="upload"
                    :multiple="false"
                    :before-upload="beforeUpload"
                    :show-file-list="false"
                    action
                    :limit="1"
                    :http-request="uploadFile"
                  >
                    <el-button>导入</el-button>
                  </el-upload>
          </div>
          <!-- 搜索区 -->
          <template slot="searchArea">
            <el-form
              :model="searchForm"
              ref="searchForm"
              label-width="107px"
              label-position="left"
              size="mini"
            >
              <el-form-item label="规则编号：">
                <el-input
                  v-model="searchForm.groupRuleCode"
                  style="width: 150px"
                ></el-input>
              </el-form-item>
              <el-form-item label="调整类型" prop="assignType">
                <el-select v-model="searchForm.assignType" 
                          placeholder="请选择" 
                          style="width:150px;"
                          @change="caliberFlagFun1">
                  <el-option
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                      :disabled="item.disabled"
                      tdList="resultData"
                      v-for="item in resultData"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="生效日期：">
                <el-date-picker
                  v-model="searchForm.effectDate"
                  value-format="yyyy-MM-dd"
                  type="date"
                  style="width: 150px"
                ></el-date-picker>
              </el-form-item>
              <el-form-item label="截止日期：">
                <el-date-picker
                  v-model="searchForm.invalidDate"
                  value-format="yyyy-MM-dd"
                  type="date"
                  style="width: 150px"
                ></el-date-picker>
              </el-form-item>
              <el-form-item label="调整方模板">
                  <el-select
                    style="width: 150px"
                    ref="a"
                    v-model="searchForm.adjTemplateId"
                    :loading="false"
                    popper-append-to-body 
                  >
                    <el-option v-for="item in templates"
                      :key="item.templateId"
                      :label="item.templateName"
                      :value="item.templateId"
                      :disabled="item.disabled"
                      :title="item.templateName"
                      tdList="templates"
                    ></el-option>
                  </el-select>
              </el-form-item>
              <el-form-item label="被调整方模板" v-if="hadjTemplateIdShow1">
                  <el-select
                    style="width: 150px"
                    ref="a"
                    v-model="searchForm.hadjTemplateId"
                    :loading="false"
                    popper-append-to-body
                  >
                    <el-option
                      :key="item.templateId"
                      :label="item.templateName"
                      :value="item.templateId"
                      :disabled="item.disabled"
                      :title="item.templateName"
                      tdList="templates"
                      v-for="item in templates"
                    ></el-option>
                  </el-select>
              </el-form-item>
              <el-form-item label="指定价格" prop="assignPrice" v-if="assignPriceShow1">
                  <el-input v-model="searchForm.assignPrice" type="text"></el-input>
              </el-form-item>
            </el-form>
          </template>
        </upper-template>
        <!-- 列表 -->
        <el-table
          ref="multipleTable"
          :data="tableData"
          style="width: 100%"
          @row-click="authorizeFor"
        >
          <el-table-column
            width="55"
            type="selection"
            
          ></el-table-column>
          <el-table-column
            prop="groupRuleCode"
            label="规则编号"
            :show-overflow-tooltip="true"
          ></el-table-column>
          <el-table-column
              label="调整类型"
              prop="assignType"
              align="center"
              header-align="center"
              :filter-multiple="true"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">
                <div>{{ assignTypeChange(scope.row.assignType) }}</div>
              </template>
          </el-table-column>
          <el-table-column
              label="调整方规则"
              align="center"
              prop="adjTemplateName"
              header-align="center"
              :filter-multiple="true"
              :show-overflow-tooltip="true"
          ></el-table-column>
          <template v-for="(item, i) in adjTitles">
              <el-table-column
                align="center"
                header-align="center"
                :filter-multiple="true"
                :key="i"
                :prop="i"
                :label="item"
                :show-overflow-tooltip="true"
              ></el-table-column>
            </template>
            <el-table-column v-if="hadjTemplateIdShow1"
              label="被调整方规则"
              align="center"
              prop="reAdjTemplateName"
              header-align="center"
              :filter-multiple="true"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <template v-for="(item, i) in reAdjTitles" >
              <el-table-column v-if="hadjTemplateIdShow1"
                align="center"
                header-align="center"
                :filter-multiple="true"
                :key="i"
                :prop="i"
                :label="item"
                :show-overflow-tooltip="true"
              ></el-table-column>
            </template>
          <el-table-column v-if="assignPriceShow1"
              label="指定价格"
              align="center"
              header-align="center"
              :filter-multiple="true"
              prop="assignPrice" 
          ></el-table-column>

          <el-table-column
            prop="effectDate"
            :show-overflow-tooltip="true"
            label="生效日期"
            sortable
          >
            <template slot-scope="scope">
              <div v-if="scope.row.effectDate">
                {{ timeFormatShort(scope.row.effectDate) }}
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>
          <el-table-column
            prop="invalidDate"
            :show-overflow-tooltip="true"
            label="生效截止日"
            sortable
          >
            <template slot-scope="scope">
              <div v-if="scope.row.invalidDate">
                {{ timeFormatShort(scope.row.invalidDate) }}
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>
          <el-table-column
            prop="creator"
            label="创建人"
            :show-overflow-tooltip="true"
          ></el-table-column>
          <el-table-column
            prop="createdTm"
            :show-overflow-tooltip="true"
            label="创建时间"
            sortable
          >
            <template slot-scope="scope">
              <div v-if="scope.row.createdTm">
                {{ timeFormat(scope.row.createdTm) }}
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>
          <el-table-column
            prop="modifier"
            :show-overflow-tooltip="true"
            label="修改人"
            sortable
            :formatter="(row) => row.modifier || '-'"
          >
          </el-table-column>
          <el-table-column
            prop="modifiedTm"
            :show-overflow-tooltip="true"
            label="修改时间"
            sortable
          >
            <template slot-scope="scope">
              <div v-if="scope.row.createdTm">
                {{ timeFormat(scope.row.modifiedTm) }}
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchForm.page"
          :page-size="searchForm.size"
          @refresh="searchFunc"
          :total="total"
        ></pagination>
      </el-col>
    </el-row>
    <!-- 新增、编辑弹窗 -->
    <el-dialog
      v-dialogDrag
      :title="titleName"
      :visible.sync="groupRuleAddAndEditDi"
      width="50%"
      top="2%"
    >
      <el-form
        :model="saveRuleForm"
        ref="saveRuleForm"
        label-width="120px"
        label-position="right"
        :rules="saveRuleFormRules"
      >
        <el-row>
          <el-col :span="10">
            <el-form-item label="规则编号：" prop="groupRuleCode">
              <el-input
                v-model.trim="saveRuleForm.groupRuleCode"
                maxlength="40"
                :disabled="ruleOperateType==2 || ruleOperateType==3"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="调整类型：" prop="assignType" required>
              <el-select v-model="saveRuleForm.assignType" @change="caliberFlagFun">
                <el-option
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.disabled"
                  tdList="resultData"
                  v-for="item in resultData"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="生效日期：" prop="effectDate">
              <el-date-picker
                v-model="saveRuleForm.effectDate"
                value-format="yyyy-MM-dd"
                type="date"
                style="width: 100%"
                :disabled="ruleOperateType==3" 
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="生效截止日：" prop="invalidDate">
              <el-date-picker
                v-model="saveRuleForm.invalidDate"
                value-format="yyyy-MM-dd"
                type="date"
                style="width: 100%"
                :disabled="ruleOperateType==3"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="指定价格：" prop="assignPrice" v-if="assignPriceShow">
                <el-input v-model="saveRuleForm.assignPrice" type="text"></el-input>
            </el-form-item>  
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="调整方模板：" prop="adjTemplateId" required>
              <el-select v-model="saveRuleForm.adjTemplateId" @change="adjTempChg">
                <el-option v-for="item in templates"
                  :key="item.templateId" :label="item.templateName"
                  :value="item.templateId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="被调整方模板：" v-if="hadjTemplateIdShow">
              <el-select v-model="saveRuleForm.hadjTemplateId" @change="hadjTempChg"
                :loading="false" popper-append-to-body
              >
                <el-option v-for="item in templates"
                  :key="item.templateId" :label="item.templateName"
                  :value="item.templateId" :disabled="item.disabled"
                  tdList="templates"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-row v-for="(value, key) in this.adjDatas" :key="key">
              <el-col>
                <dynamicForm :dataOriginProps="value" :key="key" ></dynamicForm>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="10">
            <template v-if="hadjTemplateIdShow">
                <el-row v-for="(value, key) in this.hadjDatas" :key="key">
                    <el-col >
                      <dynamicForm :dataOriginProps="value" :key="key" ></dynamicForm>
                    </el-col>
                </el-row>
            </template>
          </el-col> 
        </el-row>
      </el-form>
      <div slot="footer" v-if="ruleOperateType != '3'">
         <el-button @click="saveFunc">确 定</el-button>
         <el-button @click="groupRuleAddAndEditDi = false">取 消</el-button>
      </div>
    </el-dialog> 
    <!-- 新增、编辑弹窗 -->
    
  </div>
</template>

<script>
import { ruleTemplate,groupRule } from "@/api/index";
import upperTemplate from "@/components/upperTemplate.vue";
import dynamicForm from "../methodRule/components/dynamicForm";
import moment from "moment";
export default {
  //定义数据
  data() {
    return {
      toFormAdjData:[], // 回显的数据
      toFormHadjData:[], // 回显的数据
      searchForm: {
        groupRuleCode:"",
        assignType: "1",
        assignPrice:"",
        adjTemplateId:"",
        hadjTemplateId:"",
        effectDate: "",
        invalidDate: "",
        ruleStatus: "1",
        page: 1,
        size: 15,
      },
      ruleOperateType: "",
      total: 0,
      titleName: "",
      groupRuleDi: false,
      tableData: [],

      headData: {},//调整方模板表头
      headDataH:{},//被调整方模板表头

       //动态表格数据
      adjTitles: [],
      reAdjTitles: [],

      adjDatas:[],//调整方模板
      hadjDatas: [],//被调整方模板

      resultData: [
        { value: "1", label: "笔对笔调整" },
        { value: "2", label: "平均价格调整" },
        { value: "3", label: "指定价格调整" },
      ],
      templates: [],
      groupRuleAddAndEditDi: false,
      //是否展示被调整模板
      hadjTemplateIdShow: true,
      hadjTemplateIdShow1: true,

      saveRuleForm: {
        groupRuleCode:"",
        ruleStatus:"1",

        effectDate: "",
        invalidDate: "",
        assignType: "",
        assignPrice:"",

        adjTemplate:{},
        reAdjTemplate:{},
        //adjData
        ruleDatas: [],
        hAdjRuleDatas: [],
      },
      //表单字段规则校验
      saveRuleFormRules: {
        groupRuleCode: [{ validator: this.validateCode, trigger: 'change' }],
        effectDate: [{ required: true, message: '此项为必输项', trigger: 'blur' }],
        invalidDate: [{ required: true, message: '此项为必输项', trigger: 'blur' },
                      { validator: this.invalidDateFun, trigger: "blur" }],
        assignType: [{ required: true, message: '此项为必输项', trigger: 'blur' }],
        adjTemplateId: [{ required: true, message: '此项为必输项', trigger: 'blur' }],
      },
      //待修改规则数据集合
      groupDatas: [],
      groupRuleCode:"",
      assignPriceShow1:"",
      assignPriceShow:""
    };
  },
  //组件引入
  components: {
    upperTemplate,
    dynamicForm
  },
  //创建初始化
  created() {
    this.templateIdsInit();
    
  },
  mounted() {},
  //监控数值变化
  watch: {

  },
  //运算
  computed: {},
  methods: {
    validateCode(rule, value, callback){
		if(this.ruleOperateType == "1"){
			if (value === '') {
				callback(new Error('此项为必输项'));
		  } else {
            let data ={groupRuleCode:this.saveRuleForm.groupRuleCode};
            groupRule.checkUsing(data).then((res) => {
              if (res.code == 200) {
                if (res.data == 'false') 
                  callback();
                  else
                      callback(new Error('此编码已存在，无法使用！'));
              }
            });
	    }
		} else callback();
	},
    //得到模板下拉框列表
    //模板类型初始化
    templateIdsInit () {
      let data = {
        templateType : "5"
      };
      ruleTemplate.findTemplataByType(data).then(res => {
        if (res.code === 200) {
          this.templates = res.datas;
          let tempId = res.datas[0].templateId;
          this.searchForm.adjTemplateId = tempId;//初始化搜索区模板id
          this.searchForm.hadjTemplateId = tempId;//初始化搜索区模板id
          this.searchFunc();
          //
          
        }
      });
    },
      
    //   点击行选中
    authorizeFor(row) {
      if (this.$refs.multipleTable) {
        this.$refs.multipleTable.clearSelection();
      }
      this.$refs.multipleTable.toggleRowSelection(row, true);
    },
    //查询列表
    groupRulePageGet() {
      groupRule.findAll(this.searchForm).then((res) => {
            if (res.code == 200) {
              this.tableData = res.datas.rows;
              this.total = res.datas.total;
              this.adjTitles = res.datas.adjFieldsAndTitles;
              this.reAdjTitles = res.datas.reAdjFieldsAndTitles;
            }
      });
    },
    //查询数据
    searchFunc() {
      if (this.searchForm.assignType === "3") {
        this.searchForm.hadjTemplateId = "";
      }
      this.groupRulePageGet();
      this.hadjTempChg(this.searchForm.hadjTemplateId);  
      this.adjTempChg(this.searchForm.adjTemplateId);  
    },
    //是否显示指定价格
    caliberFlagFun(val) {
      if (val == "3") {
        this.assignPriceShow = true;
        this.hadjTemplateIdShow = false;
        this.saveRuleForm.hadjTemplateId = "";
      } else {
        this.assignPriceShow = false;
        this.hadjTemplateIdShow = true;
        this.saveRuleForm.hadjTemplateId = this.searchForm.hadjTemplateId;
      }
    },
    caliberFlagFun1(val) {
      if (val == "3") {
        this.assignPriceShow1 = true;
        this.hadjTemplateIdShow1 = false;
        this.searchForm.hadjTemplateId = "";
      } else {
        this.assignPriceShow1 = false;
        this.hadjTemplateIdShow1 = true;
        this.searchForm.hadjTemplateId = this.templates[0].templateId;
      }
    },
    assignTypeChange(rows) {
      if (rows === "1") {
        return "笔对笔调整";
      } else if (rows === "2") {
        return "平均价格调整";
      } else if (rows === "3") {
        return "指定价格调整";
      }
    },
     
    //事件转换
    timeFormat(val) {
      if (val) return moment(val).format("YYYY-MM-DD HH:mm:ss");
      else return "";
    },
    timeFormatShort(val) {
      if (val) return moment(val).format("YYYY-MM-DD");
      else return "";
    },
    //页码值改变
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.searchForm.size = val;
      this.searchFunc();
    },
    //当前页改变
    handleCurrentChange(val) {
      this.searchForm.page = val;
      console.log(`当前页: ${val}`);
      this.searchFunc();
    },
    
    emptydataTableForm() {
      this.saveRuleForm.adjTemplateId = this.searchForm.adjTemplateId;
      this.saveRuleForm.hadjTemplateId = this.searchForm.hadjTemplateId;
      this.saveRuleForm.assignPrice = "";
      this.saveRuleForm.assignType = this.searchForm.assignType;
      this.saveRuleForm.effectDate = "";
      this.saveRuleForm.invalidDate = "";
      this.saveRuleForm.groupRuleCode = "";
      this.saveRuleForm.ruleDatas = [];
      this.saveRuleForm.hAdjRuleDatas = [];
      this.saveRuleForm.adjTemplate = {};
      this.saveRuleForm.reAdjTemplate = {};
      
      this.caliberFlagFun(this.searchForm.assignType);
      this.adjTempChg(this.saveRuleForm.adjTemplateId);
      this.hadjTempChg(this.saveRuleForm.hadjTemplateId);
    },
    //新增、编辑弹窗
    addOrEditFunc(val) {
      this.ruleOperateType = val;
      // 调用toForm回显接口
      this.getMethodRuleToForm();

      if (this.ruleOperateType === "1") {
        //清空表单
        this.emptydataTableForm();
        
        this.titleName = "新增组合定价规则信息";
        this.groupRuleAddAndEditDi = true;
        this.$nextTick(() => {
        //清除校验结果
        this.$refs.saveRuleForm.clearValidate();
      });
        

      } else if (this.ruleOperateType === "2") {
        let selection = this.$refs.multipleTable.selection;
        if (selection.length < 1) {
          return this.$message.warning("请选择一条数据");
        } else if (selection.length > 1) {
          return this.$message.warning("只能选择一条数据");
          
        } else {
          
          let selectObj = selection[0];
          this.groupRuleAddAndEditDi = true;
          this.titleName =  "编辑组合定价规则信息";
          
          this.saveRuleForm = Object.assign({},this.saveRuleForm,selection[0]);

          let objAdjtmp = {};
           objAdjtmp = this.templates.filter(function (c) {
              if (c.templateName == selectObj.adjTemplateName) {
                return c
              }
            })
          this.saveRuleForm.adjTemplateId = objAdjtmp[0].templateId;

          let objReAdjtmp = {};
           objReAdjtmp = this.templates.filter(function (c) {
              if (c.templateName == selectObj.reAdjTemplateName) {
                return c
              }
           })
          this.saveRuleForm.hadjTemplateId = objReAdjtmp[0].templateId;
          
          
        }
      }
    },
    // 编辑：获取回显数据
    getMethodRuleToForm() {
      let selection = this.$refs.multipleTable.selection;
      //编辑
      if(this.ruleOperateType == '2'){
        if(selection.length !="1"){
          this.$message.warning("请选择一条数据")
          return
        }
       this.groupRuleCode = selection[0].groupRuleCode;

       let params = {
        groupRuleCode: this.groupRuleCode,
        templateId: this.searchForm.adjTemplateId
       }
       groupRule.toForm(params)
        .then((res) => {
          if (res.code === 200) {
            this.toFormAdjData = res.datas[1];
            this.toFormHadjData = res.datas[0];
            console.log(res.datas[1],"===res.datas[1]");
            console.log(res.datas[0],"===toFormHadjData");

            for(let i = 0;i<this.toFormAdjData.length;i++){
              for(let val in this.adjDatas){
                if(this.toFormAdjData[i].key == val){
                  let code = this.toFormAdjData[i].code;
                 
                  if(this.adjDatas[val].elementDataMap.elementType=='5'){
                    this.$set(this.adjDatas[val],this.adjDatas[val].templateFieldId+'L', code.substr(0,code.length - 1));
                    this.$set(this.adjDatas[val],this.adjDatas[val].templateFieldId+'R', code.substr(code.length - 1,1));
                  } else {
                    this.$set(this.adjDatas[val],this.adjDatas[val].templateFieldId,code);
                  }
                }
              }
            }

            for(let i = 0;i<this.toFormHadjData.length;i++){
              for(let val in this.hadjDatas){
                if(this.toFormHadjData[i].key == val){
                  let code = this.toFormHadjData[i].code;
                  console.log(code,"===hcode");
                  if(this.hadjDatas[val].elementDataMap.elementType=='5'){
                    this.$set(this.hadjDatas[val],this.hadjDatas[val].templateFieldId+'L',code.substr(0,code.length - 1));
                    this.$set(this.hadjDatas[val],this.hadjDatas[val].templateFieldId+'R',code.substr(code.length - 1,1));
                  } else {
                    this.$set(this.hadjDatas[val],this.hadjDatas[val].templateFieldId,code)
                  }
                }
              }
            }

          }
        });
      }
    },
     
    //保存
    saveFunc() {
      this.$refs["saveRuleForm"].validate((valid) => {
        if (valid) {
          //校验：笔对笔调整时，调整方模板必须包含账号字段！
          let assignType = this.saveRuleForm.assignType;
          if(assignType=='1'){
            let flag = false;
            let adjTemplateId  = this.saveRuleForm.adjTemplateId;
            let hadjTemplateId  = this.saveRuleForm.hadjTemplateId;
            //判断调整方模板
            groupRule.findFieldsByTemplateId({templateId: adjTemplateId}).then((res) => {
              if (res.code === 200) {
                console.log(res.data.indexOf("accountNum"),"--1-111");
                if(res.data.indexOf("accountNum")==-1){
                  flag = true;
                }
              } 
            });
            if(flag){
              this.$messager.warning("笔对笔调整规则所选择的调整方模板中必须包含账号字段！");
			        return false;
            }
            //判断被调整方模板
            groupRule.findFieldsByTemplateId({templateId: hadjTemplateId}).then((res) => {
              if (res.code === 200) {
                if(res.data.indexOf("accountNum")==-1){
                  flag = true;
                }
              } 
            });
            if(flag){
              this.$messager.warning("笔对笔调整规则所选择的被调整方模板中必须包含账号字段！");
			        return false;
            }
          }


          //调整方模板
          let groupDatas = [];
          let ruleValue = '';
          for (var keyHeadData in this.adjDatas) {
            if(this.adjDatas[keyHeadData].elementDataMap.elementType=='5'){
              ruleValue = this.adjDatas[keyHeadData][keyHeadData+'L']+this.adjDatas[keyHeadData][keyHeadData+'R']
            } else {
              ruleValue = this.adjDatas[keyHeadData][keyHeadData];
            } 

            let map = {
              templateFieldId: keyHeadData,
              ruleValue: ruleValue,
            };
            groupDatas.push(map);
          }
          this.saveRuleForm.ruleDatas = groupDatas;
          this.saveRuleForm.adjTemplate.templateId = this.saveRuleForm.adjTemplateId;

          //被调整方模板
            this.saveRuleForm.reAdjTemplate.templateId = this.saveRuleForm.hadjTemplateId;
            let hDatas = [];
            let hruleValue = '';
            if(this.saveRuleForm.assignType != '3'){
              for (var keyData in this.hadjDatas) {
                if(this.hadjDatas[keyData].elementDataMap.elementType=='5'){
                  hruleValue = this.hadjDatas[keyData][keyData+'L']+this.hadjDatas[keyData][keyData+'R']
                } else {
                  hruleValue = this.hadjDatas[keyData][keyData];
                } 
                let map = {
                  templateFieldId: keyData,
                  ruleValue: hruleValue,
                };
                hDatas.push(map);
              }
            } else {
              this.saveRuleForm.reAdjTemplate = {};
            }
            this.saveRuleForm.hAdjRuleDatas = hDatas;
          
          let data = {
            operateType: this.ruleOperateType,
            groupRule: { ...this.saveRuleForm },
          };
          groupRule.save(data).then((res) => {
            if (res.code === 200) {
              this.groupRuleAddAndEditDi = false;
              this.$message.success("保存成功");
              this.searchFunc();
            } else {
              this.$message.error(res.message || "保存失败");
            }
          });
        } else {
          this.$message.warning("请填写正确的信息！");
        }
      });
    },
    // 删除
    delFunc() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length < 1) {
        return this.$message.warning("请选择要删除的数据");
      }
      this.$confirm("您确定要删除选中数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let data = { ids: selection.map((v) => v.groupRuleCode) };
          groupRule.remove(data).then((res) => {
            if (res.code == 200) {
              this.$message.success("删除成功");
              this.searchFunc();
            } else {
              this.$message.error(res.message || "删除失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    adjTempChg(e){
      ruleTemplate
        .findFieldListByTemplateId({ templateId: e })
        .then((res) => {
          if (res.code === 200) {
            this.adjDatas = res.datas.fieldValues;
          }
        });
    },

    hadjTempChg(e){
      ruleTemplate
        .findFieldListByTemplateId({ templateId: e })
        .then((res) => {
          if (res.code === 200) {
            this.hadjDatas = res.datas.fieldValues;
          }
        });
    },
    invalidDateFun(rule, value, callback){
    	var effectDate = this.saveRuleForm.effectDate;
      var date1 = new Date(Date.parse(effectDate.replace("-","/")));
      var date2 = new Date(Date.parse(value.replace("-","/")));
		
      if (date1 > date2) {
        return callback(new Error("生效截止日必须大于等于生效日期!"));
      } else callback();
    },
 
   
    //导出文件
    exportExcel(tmpFlag) {
      let selection = this.$refs.multipleTable.selection;

      let param = {
        hasTemplete: tmpFlag, //1为导出模板
        groupRuleCode: this.searchForm.groupRuleCode,  
        effectDate: this.searchForm.effectDate,
        invalidDate: this.searchForm.invalidDate,
        assignPrice: this.searchForm.assignPrice,
        assignType: this.searchForm.assignType,
        adjTemplateId : this.searchForm.adjTemplateId,
        hadjTemplateId:this.searchForm.hadjTemplateId,
        selectedData: selection.map((v) => v.groupRuleCode)
      };

      groupRule
        .exp(param)
        .then((res) => {
          if (res) {
            var filename = decodeURI(res.headers["content-disposition"]).split("=")[1];
            let contenttype =
              filename.substring(filename.lastIndexOf("."), filename.length) === "xlsx"
                ? "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
                : "application/vnd.ms-excel;charset=utf-8";
            const content = res.data;
            const blob = new Blob([content], {
              type: contenttype,
            });
            let url = window.URL.createObjectURL(blob);
            let link = document.createElement("a");
            link.style.display = "none";
            link.href = url;
            link.setAttribute("download", filename);
            document.body.appendChild(link);
            link.click();
          }
        })
        .catch(function (error) {
          console.log(error);
          // this.$message.error("导出失败！");
        });
    },
     // 上传文件之前的钩子
    beforeUpload(file) {
      let name = file.name;
      let type = name.substring(name.lastIndexOf("."), name.length);
      if (type === ".xls" || type === ".xlsx") {
        return true;
      } else {
        this.$message.warning("只能选择xls或者xlsx格式的文件上传");
        return false;
      }
    },
     // 上传文件
    uploadFile(item) {
      let form = new FormData();
      // 文件对象
      form.append("excelFile", item.file);
      // 发送请求
      groupRule.imp(form)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success("导入成功");
            this.searchFunc();
          } else {
            this.$message.error(res.message);
          }
          this.$refs.upload.clearFiles();
        })
        .catch((err) => {
          this.$refs.upload.clearFiles();
        });
    },








  }
  

};
</script>


<style lang="scss" scoped>
.buessinessEleTable .el-table__header th {
  /deep/ .cell {
    white-space: nowrap !important;
  }
}

/deep/.el-dialog__body {
  max-height: 400px;
}
.tipMessage {
  line-height: 32px;
  margin-left: 5px;
  color: red;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500 !important;
  font-size: 12px !important;
}
.selectBox {
  background: url("~@/assets/images/select_btn.gif");
  background-repeat: no-repeat;
  height: 26px;
  width: 23px;
  position: absolute;
  right: 0;
  top: 5px;
  cursor: pointer;
}
/deep/.el-popover {
  max-height: 160px;
  overflow: auto;
}

.right {
  float:right;
  width:50%
}

.left {
  float:left;
  width:50%
}
</style>